/*
 * @Description: loading组件
 * @Author: chaizhou
 * @Date: 2023-02-21 16:19:14
 * @LastEditTime: 2023-02-28 14:28:47
 */

import { ElLoading } from "element-plus";

/**
 * @description:
 * @param {*} fn fn是同步方法，结束后隐藏loading；异步方法，resolve后隐藏loading
 * @param {*} options 配置项
 * @return {*}
 */
export const withLoading = (fn, options = {}) => {
  let loading;
  const showLoading = (options) => {
    loading = ElLoading.service(options);
  };

  const hideLoading = () => {
    if (loading) {
      loading.close();
    }
  };
  const newFn = (...args) => {
    // 元素不存在
    if (
      typeof options?.target === "string" &&
      !document.querySelector(options?.target)
    )
      return;
    try {
      showLoading(
        Object.assign(
          {
            lock: true,
            text: "数据加载中",
            background: "rgba(0, 0, 0, 0.1)",
          },
          options
        )
      );
      const result = fn(...args);
      if (!(result instanceof Promise)) {
        hideLoading();
        return result;
      }
      return result
        .then((res) => {
          hideLoading();
          return res;
        })
        .catch((err) => {
          hideLoading();
          throw err;
        });
    } catch (err) {
      hideLoading();
      throw err;
    }
  };
  return newFn;
};
